<template>
  <div class="app-container">
    <div class="container-bg">
      <div class="filter-container">
        <el-input v-model="listQuery.name" placeholder="姓名" style="width: 120px" class="filter-item"/>
        <el-select v-if="false" style="width: 120px" v-model="listQuery.iLoadComplete" placeholder="请选择人员状态"
                   @change="doGetCommunityPersons" class="filter-item m-margin-l10">
          <el-option v-for="(v, i) in personStatus" :key="v.value" :label="v.name" :value="v.value"/>
        </el-select>
        <el-date-picker style="width: 380px" class="filter-item m-margin-l10" v-model="dateTime" type="datetimerange"
                        :editable="false" range-separator="~" value-format="yyyy-MM-dd HH:mm:ss"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期" :picker-options="pickerOptions"
                        :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
        <el-select  style="width: 200px" v-model="listQuery.loadCompleted" placeholder="请选择特征值状态"
                   class="filter-item m-margin-l10">
          <el-option v-for="(v, i) in eigenvalueStatus" :key="v.value" :label="v.name" :value="v.value"/>
        </el-select>
        <el-button class="filter-item m-margin-l10" type="primary" icon="el-icon-search" @click="onSearch">查询
        </el-button>
        <el-button class="filter-item m-margin-l10" type="warning" icon="el-icon-refresh" @click="onReset">重置
        </el-button>
        <div style="float: right; display: flex"  v-if="isAdmin">
          <el-button class="m-margin-l10" icon="el-icon-edit" type="primary" @click="addDevice('2')" v-if="false">设备注册
          </el-button>
          <el-button class="m-margin-l10" icon="el-icon-edit" type="primary" @click="addCommunityPerson('2')" v-if="false">批量注册
          </el-button>
          <el-button class="m-margin-l10" icon="el-icon-edit" type="primary" @click="addCommunityPerson(1)">单人注册
          </el-button>
        </div>
      <!-- </div> -->
      <!-- <el-alert
        style="margin-bottom: 10px;width: 40%"
        title="请注意，按时间查询以人员生效开始时间为查询条件"
        type="info">
      </el-alert> -->
        <div style="float: right; display: flex"  v-if="isAdmin">
        <!-- <div> -->
          <el-button icon="el-icon-delete" class="filter-item" type="danger" plain
                     @click="doDeleteCommunityPersonSelect">批量删除
          </el-button>
          <el-button icon="el-icon-delete" class="filter-item" type="danger"
                     @click="doDeleteCommunityPersonAll">全部清除
          </el-button>
          <!-- <el-popconfirm
            cancel-button-text="不用了"
            confirm-button-text="好的"
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除当前选中人员吗？"
            @confirm="doDeleteCommunityPerson"
          >
            <el-button
              slot="reference"
              icon="el-icon-delete"
              class="filter-item"
              type="danger"
              >批量删除
            </el-button>
          </el-popconfirm> -->
          <el-button class="filter-item" style="margin-left: 10px" type="success" @click="doDownloadFile"
                     v-if="false"
                     :disabled="personData.total == 0">导出
          </el-button>
        </div>
      </div>
      <div style="width: 50%">
        <el-row>
          <el-col :span="12" align="center">
            <el-tag>
              当前数量<br/>
              <!--                <div style="white-space: nowrap;">成功:{{  faceCount.success?faceCount.success:'&#45;&#45;'}} &nbsp;&nbsp;&nbsp; 等待:{{ faceCount.waiting? faceCount.waiting:'&#45;&#45;'}} &nbsp;&nbsp;&nbsp;  失败:{{ faceCount.failed?faceCount.failed:"&#45;&#45;" }}</div>-->
              <div style="white-space: nowrap">
                人员数量：{{
                  faceCount.faceCount ? faceCount.faceCount : "0"
                }}
                / 特征值成功数量：{{
                  faceCount.identityCount ? faceCount.identityCount : "0"
                }}
                / 特征值失败数量：{{
                  faceCount.faceCountFailed ? faceCount.faceCountFailed : "0"
                }}
              </div>
            </el-tag>
          </el-col>
          <el-col :span="12" align="center">
            <el-tag>
              总容量
              <br/>
              {{ faceCount.devicesCount ? faceCount.devicesCount : "--" }}
            </el-tag>
          </el-col>
        </el-row>
      </div>
      <el-table :data="personData.list" border fit highlight-current-row 
        v-loading="loading"
        element-loading-text="正在加载数据，请耐心等待"
        :max-height="600"
        :min-height="500"
      @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40"></el-table-column>
        <!-- <el-table-column
          label="序号"
          prop="id"
          width="100px"
          align="center"
        ></el-table-column> -->
        <el-table-column v-if="false" align="center" label="照片" width="100px">
          <template slot-scope="scope">
            <el-image style="width: 60px; height: 60px; border-radius: 50%" ref="lazyImg" fit="cover"
                      :src="localOrigin + scope.row.sLocalPicturePath" class="vx-lazyLoad" lazy>
              <div slot="placeholder" class="image-slot">
                <i class="el-icon-loading"></i>加载中
              </div>
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="人员ID" show-overflow-tooltip width="450">
          <template slot-scope="scope">{{ scope.row.personId }}</template>
        </el-table-column>
        <el-table-column align="center" label="姓名" show-overflow-tooltip width="130">
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column align="center" label="类型" v-if="false">
          <template slot-scope="scope">{{ scope.row.sType | sType }}</template>
        </el-table-column>
        <el-table-column align="center" class-name="status-col" label="生效时间" prop="sRegistrationTime">
          <template slot-scope="scope">
            <span>{{ scope.row.effectiveStartTime }} </span>
            <span style="margin: 0 10px">~</span>
            <span>{{ scope.row.validEndTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="特征值状态" width="150">
          <template slot-scope="scope">{{ scope.row.loadCompleted | loadCompleted }}</template>
        </el-table-column>
        <el-table-column align="center" class-name="status-col" label="操作" width="240">
          <template slot-scope="{ row, $index }">
            <el-row>
              <el-button v-if="isAdmin" size="mini" class="light_blue_btn" @click="editCommunityPerson(row, $index)">修改
              </el-button>
              <el-button type="success" size="mini" @click="goDetails(row, $index)">查看
              </el-button>
              <el-popconfirm v-if="isAdmin" cancel-button-text="不用了" class="m-margin-l10" confirm-button-text="好的"
                             icon="el-icon-info"
                             icon-color="red" title="您确定删除当前人员吗？" @confirm="doDeleteCommunityPerson">
                <el-button slot="reference" size="mini" class="light_red_btn" @click="deleteCommunityPerson(row)">删除
                </el-button>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <pagination :limit.sync="listQuery.limit" :page.sync="listQuery.page" :total="personData.total"
                  :page-sizes="[20, 100, 500]" @pagination="changePage"/>
    </div>
    <!-- 单个添加人员 -->
    <el-dialog :visible.sync="dialogFormVisible" v-if="dialogFormVisible" width="740px" :title="drTitle" class="frame"
               :close-on-click-modal="false" @close="onClose">
      <el-form class="el-form-box" ref="dataForm" :model="form" :rules="rules" label-position="left" label-width="120px"
               style="margin: 0 50px">
        <el-form-item label="人员ID" prop="personId">
          <el-input v-model.trim="form.personId" placeholder="请输入人员ID" v-bind:disable="disID" :disabled="drTitle=='单人修改'"/>
        </el-form-item>
        <el-form-item label="特征类型" prop="identityType">
          <el-select v-model="form.identityType" placeholder="请选择" type="number" clearable>
            <el-option
              v-for="item in identityType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="effectivedate">
          <el-date-picker @input="$forceUpdate()" v-model="form.effectivedate" type="datetimerange" range-separator="-"
                          start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"
                          :default-time="['00:00:00', '23:59:59']"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入姓名" maxlength="20"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择" type="number">
            <el-option label="未知" :value="0"></el-option>
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="通行卡" prop="thirdpartyId" v-if="this.form.identityType == 3 && this.form.infoType">
          <el-input v-model.trim="form.thirdpartyId" placeholder="请输入通行卡" maxlength="20"/>
        </el-form-item>
        <div style="width: 300px;margin-top: 10px" v-if="this.form.method == 1">
          <el-upload
            :file-list="imageList"
            :auto-upload="false"
            ref="uploadImg"
            action=""
            accept=".png,.jpg,.jpeg"
            :limit='1'
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="getFile"
          >
            <el-button type="primary" size="small"><i class="el-icon-plus"></i>上传图片</el-button>
          </el-upload>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCommunityPersonInfo()">提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 批量添加 -->
    <el-dialog :visible.sync="dialogFormGroup" title="批量添加" :close-on-click-modal="false" v-if="dialogFormGroup"
               :before-close="handleBeforeClose" :destroy-on-close="true">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="上传资料" name="first">
          <el-alert
            title="请注意，上传文件的过程中，关闭此弹窗可能会导致传输失败,请确保文件传输完成后，再点击确定、取消或者右上角的交叉按钮"
            type="warning">
          </el-alert>
          <el-form ref="dataForm" :model="form" :rules="rules" label-position="left" label-width="200px">
            <el-form-item label="是否可以上传" prop="type">
              <div class="pro-loading">
                <div v-if="!progress.available" style="margin-top: -10px">
                  正在获取进度信息...
                </div>
                <div v-else-if="progress.available == 0">
                  <el-progress
                    :percentage="
                                  (progress.count / progress.total_count) * 100
                                    ? (
                                        (progress.count / progress.total_count) *
                                        100
                                      ).toFixed(2)
                                    : 0
                                "
                  />
                </div>
                <div
                  v-else-if="progress.available == 1"
                  style="margin-top: -10px"
                >
                  暂时没有人升级，您可以上传
                </div>
              </div>
            </el-form-item>
            <el-form-item label="模板" prop="type">
              <el-button size="small" type="primary" @click="downloadTemplate"
                         :disabled="progress.available && progress.available == 0">
                1.获得模板
              </el-button>
            </el-form-item>
            <el-form-item label="上传文件" prop="type" label-width="400">
              <div style="width: 600px; display: flex; flex-direction: row">
                <el-upload class="upload-demo" ref="upload" action="" accept=".xls,.xlsx" :on-remove="handleRemoveGroup"
                           v-if="isShowUpload1"
                           :limit="1"
                           :on-change="handleSuccessGroup" :on-exceed="handleExceed" :file-list="fileListGroup"
                           style="margin-left: 20px;max-width: 300px"
                           :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary"
                             :disabled="progress.available && progress.available == 0">2.选取表格
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传.xls或.xlsx文件
                    <!-- ，且不超过500kb-->
                    <!-- (已选择个-->
                    <!--<strong>{{ imgLimit }}</strong-->
                    <!-- >/10000 文件)-->
                  </div>
                </el-upload>
                <el-upload :disabled="isUploadImageDisabled" style="margin-left: 20px;max-width: 300px"
                           class="upload-demo" ref="upload" v-if="isShowUpload2"
                           action="" accept=".jpg,.png,.jpeg,.jp2" :multiple="true" :limit="10000"
                           :on-remove="handleRemoveGroup2"
                           :on-change="handleSuccessGroup2" :on-exceed="handleExceed2" :file-list="fileListGroup2"
                           :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary" :disabled="isUploadImageDisabled">{{
                      isUploadImageDisabled
                        ? `3.选取图片（必须先完成第2步）`
                        : `3.选取图片`
                    }}
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    只能上传.jp2（掌静脉） .png（人脸）或.jpeg(人脸)文件，<br/>且不超过500kb ,(已选择个<strong>{{
                      imgLimit
                    }}</strong>/10000 文件)
                  </div>
                </el-upload>
                <div style="height: 100px">
                  <el-button style="margin-left: 20px;max-width: 300px" size="small" type="primary"
                             @click="handleImageUpload" :loading="fourthStepLoading"
                             :disabled="isUploadImageDisabled2">
                    4.上传图片-已经上传成功了的数量：{{ totalSuccess }}
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="图片剩余记录" name="second">
          <picture-rest-record @getFaceCount="getFaceCount"></picture-rest-record>
        </el-tab-pane>
        <el-tab-pane label="错误记录" name="third">
          <error-record ref="errorlistRef" @getFaceCount="getFaceCount"></error-record>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer" v-if="activeName == `first`">
        <el-button @click="handleBeforeClose" :disabled="groupLoading">取消
        </el-button>
        <el-button :disabled="(progress.available && progress.available == 0)||isConfirmDisable" type="primary"
                   @click="submitUploadGroup()"
                   :loading="groupLoading">完成
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" :destory-on-close="true">
      <img :src="dialogImageUrl" alt="" width="100%"/>
    </el-dialog>
    <el-dialog title="失败文件提示" :visible.sync="dialogTableVisibleFail" :close-on-click-modal="false"
               @close="turnGetList">
      <el-table :data="failList" style="width: 100%; max-height: 600px">
        <el-table-column property="name" label="姓名" align="left" show-overflow-tooltips></el-table-column>
        <el-table-column property="iLoadCompleted" label="原因" align="left">
          <template slot-scope="scope">无效特征值</template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <DeviceDialog ref="deviceDialogRef"/>
  </div>
</template>

<script>
  import Cookies from 'js-cookie'
import {
  getBase64,
  getFacePersonsListApi,
  personsUploadApi,
  addFacePersonsApi,
  editFacePersonsApi,
  delFacePersonsApi,
  getFacePersonsListNamesApi,
  getLastFaceApi,
  getFaceWaitingApi,
  getFaceCheckIdsApi,
  getFacePersonsApi,
  faceListExportUrlApi,
  clearAllUserApi,
  getErrorList,
  doDelError,
  doDelErrorMultiple,
  clearAllErrors,
  getPersonTemplate,
  uploadPerson,
  uploadImage,
  getErrorList2,
  doDelError2,
  doDelErrorMultiple2,
  clearAllErrors2,
  predictSubmitStatusApi,
  getFaceCountApi,
  controlRecordExportUrlApi,
} from "@/api/community/communityPerson";
import {downloadFile} from "@/api/file/file";
import ExcelUpload from "./component/ExcelUpload";
import Pagination from "@/components/Pagination";
import FileSaver from "file-saver";

import excelUtil from "@/utils/dealwithExcelUtil.js";
import {cnReg} from "@/utils/validate.js";

import {
  getPersonList,
  addPerson,
  editEventIdentity,
  // getEventIdentity,
  fileUpload,
  fileUploadApi,
  delUploadPicApi,
} from "@/api/community/person";
import {parseTime} from "@/utils/ruoyi";
import {downloadBoldFile} from "@/api/common";

import DeviceDialog from "@/views/person/person/sub/deviceDialog.vue";
import {mapGetters, mapMutations} from 'vuex'
import PictureRestRecord from "@/views/person/person/sub/pictureRestRecord.vue";
import ErrorRecord from "@/views/person/person/sub/errorRecord.vue";

const rules = {
  personId: [
    {
      trigger: ["blur"],
      required: true,
      message: "人员ID不能为空",
    },
    {
      pattern:
        /^[A-Za-z0-9]{1,32}$/,
      message: "1-32位,同时包含数字、大小写字母",
      trigger: "blur",
    },
  ],
  identityType: [
    {
      trigger: ["change"],
      required: true,
      message: "特征类型不能为空",
    },
  ],
  name: [
    {
      trigger: ["blur", "change"],
      required: true,
      message: "姓名不能为空",
      // pattern: cnReg,
    },
  ],
  gender: [
    {
      trigger: ["blur", "change"],
      required: true,
      message: "性别不能为空",
      // pattern: cnReg,
    },
  ],
  thirdpartyId: [
    {
      trigger: ["blur", "change"],
      required: true,
      message: "不能为空",
      // pattern: cnReg,
    },
  ],
  sTelephoneNumber: [
    {
      required: false,
      message: "手机号码不能为空",
      trigger: ["blur"],
    },
    {
      pattern: /^1[0-9]\d{9}$/,
      message: "请输入正确的号码",
      trigger: ["blur"],
    },
  ],
  sCertificateNumber: [
    {
      trigger: ["blur", "change"],
      required: false,
      message: "请填写身份证信息",
    },
    {
      pattern: /(^\d{18}$)|(^\d{15}$)/,
      message: "请输入正确的身份证",
      trigger: ["blur", "change"],
    },
  ],
  effectivedate: [
    {
      trigger: "blur",
      required: true,
      message: "请选择生效日期",
    },
  ],
  iAccessCardNumber: [
    {
      trigger: "blur",
      required: true,
      message: "请输入门禁卡号",
    },
  ],
};

let rangDate = [
  new Date(),
  new Date(
    new Date().getFullYear() + 3,
    new Date().getMonth(),
    new Date().getDate(),
    23,
    59,
    59
  ),
];

export default {
  name: "CommunityPerson",
  components: {ErrorRecord, PictureRestRecord, Pagination, ExcelUpload, DeviceDialog},
  data: function () {
    return {
      isAdmin: false,
      drTitle:'',
      imageList: [],
      isShowUpload1: true,
      isShowUpload2: true,
      isConfirmDisable: true,
      totalSuccess: 0,
      fourthStepLoading: false,
      isUploadImageDisabled: true,
      isUploadImageDisabled2: true,
      faceCount: {},
      facePath: '',
      ipersonId: '',
      infoType: false,
      disID: false,
      info3thName: '通行证号码',
      identityType: [
        {
          value: '1',
          label: '人脸'
        }, {
          value: '2',
          label: '掌静脉',
          disabled: true
        }, {
          value: '3',
          label: '通行卡',
          disabled: true
        }, {
          value: '4',
          label: '密码',
          disabled: true
        }, {
          value: '5',
          label: '掌纹',
          disabled: true
        }, {
          value: '6',
          label: '虹膜',
          disabled: true
        }, {
          value: '7',
          label: '指纹',
          disabled: true
        }, {
          value: '8',
          label: '指静脉',
          disabled: true
        }
      ],

      progress: {},
      isSubmitDisable: false,
      isDoMultipleDel: false,
      isDoMultipleDel2: false,
      activeName: "first",
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      rules,
      hideUpload: false,
      fit: "contain",
      personData: {list: [], total: 0},
      listQuery: {
        name: "",
        beginTime: "",
        endTime: "",
        loadCompleted: -999,
        limit: 20,
        page: 1,
      },
      loading: true,
      machineQuery: {
        page: 1,
        row: 10,
        communityId: "",
      },
      limitCount: 1,
      form: {
        effectiveStartTime: "2023-02-28 09:11:26",
        name: "",
        validEndTime: "2026-02-28 23:59:59",
        loadCompleted: -999,
        effectivedate: ["2023-02-28 09:11:26", "2025-02-28 23:59:59"],
      },
      selectList: [],
      // 门禁A设备
      machine: {
        list: [],
        total: 0,
      },
      toMachinePerson: {
        personId: "",
        machineId: "",
      },
      fileList: [],
      dialogVisible: false,
      dialogFormVisible: false,
      dialogFormGroup: false,
      groupLoading: false,
      dialogImageUrl: "",
      uploadDialogVisible: false,
      fileForm: undefined,
      sTypeArr: [
        {name: "白名单", value: "whiteList"},
        {name: "黑名单", value: "blackList"},
        // {name:'访客',value:'tourist'},
      ],
      dateTime: [],
      srcList: [],
      fileListGroup: [],
      fileListGroup2: [],
      checkId: 0,
      failList: [],
      isAdd: "add",
      dialogTableVisibleFail: false, //失败文件
      singleLoading: false,
      percentage: 0,
      scaleTage: 0,
      intervalTime: null,
      showprogress: false,
      personStatus: [
        {name: "成功人员", value: "1"},
        {name: "等待人员", value: "0"},
        {name: "失败人员", value: "-1"},
      ],
      eigenvalueStatus: [
        {name: "全部", value: -999},
        {name: "成功", value: 1},
        {name: "失败", value: -1},
        {name: "待生成", value: 0},
      ],
    };
  },
  created() {
    this.isAdmin=Cookies.get('roleId')*1>1?false:true
    console.log(this.$store.state.user.yhglForm,'this.$store.state.user.yhglForm');
    if(JSON.stringify(this.$store.state.user.yhglForm) != '{}'){
      let obj = this.$store.state.user.yhglForm
      this.listQuery.name = obj.name
      this.dateTime = obj.dateTime
      this.listQuery.loadCompleted = obj.loadCompleted
      this.listQuery.limit = obj.limit
      this.listQuery.page = obj.page
      this.$store.commit('setYhglForm',{})
    }
    this.doGetCommunityPersons();
    this.getFaceCount();
  },
  watch: {
    dialogFormVisible: function (val) {
      if (val === false) {
        this.form = {
          personId: "",
          name: "",
          tel: "",
          idNumber: "",
          type: "",
          sLocalPicturePath: "",
        };
        this.fileList = [];
      }
    },
    showprogress: {
      handler(n, o) {
        if (n) {
          this.increase();
        } else {
          this.increaseend();
        }
      },
      deep: true,
    },
  },
  filters: {
    sType(val) {
      switch (val) {
        case "whiteList":
          return "白名单";
        case "blackList":
          return "黑名单";
        default:
          return "访客";
      }
    },
    loadCompleted(val) {
      switch (val) {
        case -1:
          return "失败";
        case 0:
          return "还未生成";
        case 1:
          return "生成成功";
      }
    },
    iLoadCompleted(val) {
      switch (val) {
        case -1:
          return "失败";
        case 0:
          return "等待";
        case 1:
          return "成功";
      }
    },
  },
  methods: {
    getPersonFace() {
      let query = {
        personId: this.personId,
        type: "facePicture",
      };
      // getEventIdentity(query).then((res) => {
      //   let list = res;
      //   list.forEach((item) => {
      //     item.url = process.env.VUE_APP_BASE_URL + item.identityData;
      //     item.name = item.identityID;
      //   });
      //   this.imageList = list;
      // });
    },
    handleBeforeClose() {
      if (this.fourthStepLoading) {
        this.$message.warning("请等待图片上传完成");
        return false
      }
      this.totalSuccess = 0
      this.isConfirmDisable = true
      this.isUploadImageDisabled = true
      this.isUploadImageDisabled2 = true
      this.isShowUpload = true
      this.isShowUpload2 = true
      window.location.reload()
      this.dialogFormGroup = false
    },
    // handleDialogFormGroupClose() {
    //   if (this.fourthStepLoading) {
    //     this.$message.warning("请等待图片上传完成");
    //     return false
    //   }
    //   this.dialogFormGroup = false
    // },
    // 人脸库容量
    getFaceCount() {
      getFaceCountApi().then((res) => {
        this.faceCount = res;
      });
    },

    //判断是否能上传
    predictSubmitStatus() {
      setInterval(() => {
        predictSubmitStatusApi({}).then((res) => {
          // console.log(res);
          // 0 被占用
          // this.isSubmitDisable = res.avilable == 0;
          this.progress = {...res};
          if (this.progress.avilable === 0) {
            this.$message.info("正在有人使用上传，请稍后");
          }
          // console.log("this.progress", this.progress);
        });
      }, 1000 * 10);
    },
    downloadTemplate() {
      let params = {
        beginTime: "",
        endTime: "",
        page: -1,
        limit: -1,
        name: "",
      };
      let downLoadfile =
        process.env.VUE_APP_BASE_URL + "/template/batch_add_template.xlsx";
      this.download(downLoadfile, new Date().getTime());
    },
    handleClick() {
      // this.doGetErrorList();
      // this.doGetErrorList2();
    },

    changePage(val) {
      let [page, limit] = [val.page, val.limit];
      this.listQuery.page = page;
      this.listQuery.limit = limit;
      this.doGetCommunityPersons();
    },
    doGetCommunityPersons() {
      this.loading = true;
      this.personData.list = [];

      this.getFaceCount()
      if (!this.dateTime) this.dateTime = [];
      this.listQuery.beginTime = this?.dateTime[0] ?? "1970-01-01 00:00:00";
      this.listQuery.endTime =
        this?.dateTime[1] ??
        this.$moment(this.$moment().endOf("day").unix() * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        );

      if (this.dateTime.length === 0) {
        this.listQuery.beginTime = "";
        this.listQuery.endTime = "";
      }
      getPersonList(this.listQuery).then((response) => {
        this.personData.list = response.data;
        let selfItems = this.personData.list;
        let self = this;
        console.log(799, selfItems);
        for (const i in selfItems) {
          selfItems[i].effectiveStartTime = self.$moment(selfItems[i].effectiveStartTime * 1000).format(
          "YYYY-MM-DD HH:mm:ss");
          selfItems[i].validEndTime = self.$moment(selfItems[i].validEndTime * 1000).format(
          "YYYY-MM-DD HH:mm:ss");
        }
        // this.personData.list = [{
        //     "effectiveStartTime":"2023-02-28 09:11:26",
        //     "fileUrl":"",
        //     "name":"大大",
        //     "passStrategyId":"",
        //     "personIDType":"1",
        //     "personId":"6D9DF6CBEF88491FB8FCE6F671A78D78",
        //     "personType":"0",
        //     "recordId":"",
        //     "registrationMethod":"1",
        //     "registrationTime":"",
        //     "reserve":"",
        //     "sNote":"",
        //     "validEndTime":"2026-02-28 23:59:59"
        // }]
        this.personData.total = response.totalCount;
        this.loading = false;
        this.$nextTick(() => {
          // 请求上一页
          if (this.listQuery.page != 1 && this.personData.list.length == 0) {
            this.changePage({page: this.listQuery.page - 1});
          }
        });
      });
    },
    onSearch() {
      this.listQuery.page = 1;
      this.listQuery.limit = 20;
      this.doGetCommunityPersons();
    },
    // 提交单个的
    saveCommunityPersonInfo() {
      var self = this;
      this.$refs.dataForm.validate((valid) => {
        console.log(777, this.form);
        if (valid) {
          self.form.identityData = this.facePath.length > 0 ? self.facePath : '';
          if (!self.form.identityData && self.form.method == 1) {
            this.$message.error('图片必须上传');
            return false;
          }
          self.singleLoading = true;
          // self.form.effectiveStartTime = parseTime(self.form.effectivedate[0]);
          // self.form.validEndTime = parseTime(self.form.effectivedate[1]).getTime();
          self.form.effectiveStartTime = this.$moment(self.form.effectivedate[0]).unix().toString();
          self.form.validEndTime = this.$moment(self.form.effectivedate[1]).unix().toString();
          delete self.form.effectivedate;
          delete self.form.idNumber;
          delete self.form.sLocalPicturePath;
          delete self.form.tel;
          delete self.form.type;
          delete self.form.loadCompleted;
          delete self.form.registrationTime;
          if (self.infoType) {
            self.form.method = 1;
          } else {
            self.form.method = 2;
          }

          self.dialogFormVisible = false;
          if (self.form.identityType != 3 && self.form.identityType != 4) {
            self.form.thirdpartyId = '';
          }
          // console.log("this.form", this.form);
          addPerson(this.form)
            .then((res) => {
              this.singleLoading = false;
              if (this.form.personId) {
                this.$message.success("修改成功");
                this.doGetCommunityPersons();

              } else {
                this.$message.success("提交成功");
              }
              this.dialogFormVisible = false;
              this.doGetCommunityPersons();
            })
            .catch((err) => {
            });
        } else {
          this.singleLoading = false;
        }
      });
    },

    onReset() {
      this.personData.list = [];
      this.personData.total = 0;
      this.listQuery = {
        beginTime: "",
        endTime: "",
        type: "all",
        gender: "all",
        minAge: 0,
        maxAge: 100,
        accessCardNumber: 0,
        beginPosition: 0,
        endPosition: 19,
        iLoadComplete: '1',
        limit: 20,
        name: "",
        page: 1,
      };
      this.dateTime = [];
      this.doGetCommunityPersons();
    },
    reset() {
      this.resetForm("form");
      this.form = {
        effectiveStartTime: "2023-02-28 09:11:26",
        name: "",
        validEndTime: "2026-02-28 23:59:59",
        loadCompleted: "",
        effectivedate: rangDate,
      };
      this.fileForm = undefined;
    },
    handleSelectionChange(value) {
      console.log("value", value);
      this.selectList = [];
      for (let i = 0; i < value.length; i++) {
        this.selectList.push({id: value[i].personId});
      }
    },
    addDevice() {
      // this.dialogFormVisible = true;
      this.$refs.deviceDialogRef.open()
    },
    // 添加人脸
    addCommunityPerson(msg) {
      if (msg == 1) {
        this.drTitle='单人新增'
        this.form.effectivedate = rangDate;
        this.form.method = 1;
        this.infoType = true;
        this.dialogFormVisible = true;
        return false;
      }
      this.dialogFormGroup = true;
      this.isShowUpload = true
      this.isShowUpload2 = true
      //判断是否能够批量上传
      this.predictSubmitStatus();
    },
    // 修改
    editCommunityPerson(_row, _index) {
      this.drTitle='单人修改'
      this.reset();
      this.singleLoading = false;
      this.infoType = false;
      this.disID = true;
      console.log();
      this.form.method = 2;
      this.ipersonId = _row.personId;
      this.form = this.$fn.deepCopy(_row);
      this.form.effectivedate = [_row.effectiveStartTime, _row.validEndTime];
      this.form.identityType = this.form.identityType.toString();
      this.dialogFormVisible = true;
      // $('.frame .el-dialog__title').text('单人修改');
    },
    // 详情页
    goDetails(val) {
      // console.log(val, 'name')
      let formObj = {
        name:this.listQuery.name,
        dateTime:this.dateTime,
        loadCompleted:this.listQuery.loadCompleted,
        limit:this.listQuery.limit,
        page:this.listQuery.page
      }
      this.$store.commit('setYhglForm',formObj);
      this.$router.push({
        name: "person-details",
        query: {id: val.personId, name: val.name},
      });
    },
    deleteCommunityPerson(_row) {
      console.log("rw", _row);
      this.selectList = [{id: _row.personId}];
    },
    doDeleteCommunityPerson() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除人员");
        return;
      }
      for (let i = 0; i < this.selectList.length; i++) {
        console.log(this.selectList);
        this.loading = true;
        delFacePersonsApi({personId: this.selectList[i].id})
          .then((res) => {
            if (i == this.selectList.length - 1) {
              this.$message.success("删除成功");
              this.doGetCommunityPersons();
              this.selectList = [];
            }
          })
          .catch((err) => {
            if (i == this.selectList.length - 1) {
              this.$message.success("删除成功");
              this.doGetCommunityPersons();
              this.selectList = [];
            }
          });
      }
    },
    doDeleteCommunityPersonSelect() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除人员");
        return;
      }
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, `此操作将永久删除所选`),
          h("i", {style: "color: #f00"}, this.selectList.length),
          h("span", null, "个人员, 是否继续?"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            console.log("1111");
            done();
          } else {
            done();
          }
        },
      }).then((action) => {
        console.log("this.selectList", this.selectList);
        // console.log(action);
        for (let i = 0; i < this.selectList.length; i++) {
          delFacePersonsApi({personId: this.selectList[i].id})
            .then((res) => {
              if (i == this.selectList.length - 1) {
                this.$message.success("删除成功");
                this.doGetCommunityPersons();
                this.selectList = [];
              }
            })
            .catch((err) => {
              if (i == this.selectList.length - 1) {
                this.$message.success("删除成功");
                this.doGetCommunityPersons();
                this.selectList = [];
              }
            });
        }
      });
      return false;

      this.$confirm(
        `此操作将永久删除所选${this.selectList.length}个人员, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          for (let i = 0; i < this.selectList.length; i++) {
            delFacePersonsApi(this.selectList[i].id)
              .then((res) => {
                if (i == this.selectList.length - 1) {
                  this.$message.success("删除成功");
                  this.doGetCommunityPersons();
                  this.selectList = [];
                }
              })
              .catch((err) => {
                if (i == this.selectList.length - 1) {
                  this.$message.success("删除成功");
                  this.doGetCommunityPersons();
                  this.selectList = [];
                }
              });
          }
        })
        .catch(() => {
          // this.$message.info("已取消删除");
        });
    },
    doDeleteCommunityPersonAll() {
      this.$confirm("此操作将永久删除所有人员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          clearAllUserApi().then((res) => {
            // console.log(res);
            this.$message.success("删除成功");
            var that = this;
            setTimeout(() => {
              that.doGetCommunityPersons();
            }, 1000);
          });
        })
        .catch(() => {
          // this.$message.info("已取消删除");
        });
    },

    // 同时提交图片
    uploadFileImg(path, oldId) {
      let formData = new FormData();
      formData.append("file", this.fileForm);
      personsUploadApi(formData, path)
        .then((response) => {
          this.doGetCommunityPersons();
        })
        .catch((err) => {
          if (this.isAdd == "add") {
            this.form.sNote = "";
            let allP = [];
            // 循环请求 是否添加成功或者失败
            for (let i = 0; i < 6; i++) {
              if (i == 0) {
                allP.push(
                  new Promise((resolve, reject) => {
                    editFacePersonsApi(this.form, oldId)
                      .then((response) => {
                        resolve(response);
                      })
                      .catch((err) => {
                        resolve(err);
                      });
                  })
                );
              } else {
                allP.push(
                  new Promise((resolve, reject) => {
                    setTimeout(() => {
                      getFacePersonsApi(oldId, new Date().getTime())
                        .then((response) => {
                          resolve(response);
                        })
                        .catch((err) => {
                          resolve(err);
                        });
                    }, 200 * i);
                  })
                );
              }
            }
            Promise.all(allP).then((res) => {
              // 有失败的就删除掉
              let flag = false;
              this.singleLoading = false;
              for (let v of res) {
                if (v.iLoadCompleted == -1) {
                  flag = true;
                }
              }
              if (flag) {
                delFacePersonsApi(oldId)
                  .then((res) => {
                  })
                  .catch((err) => {
                    this.$message.error("获得照片特征值失败，请更换照片");
                  });
              } else {
                this.dialogFormVisible = false;
                this.$message.success("新增成功");
                this.turnGetList();
              }
            });
          } else {
            this.singleLoading = false;
            this.turnGetList();
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
          }
        });
    },
    doDownloadFile() {
      let params = {
        beginTime: "",
        endTime: "",
        page: -1,
        limit: -1,
        name: "",
      };
      faceListExportUrlApi(params).then((res) => {
        let downLoadfile = process.env.VUE_APP_BASE_URL + res.url;
        this.download(downLoadfile, new Date().getTime());
      });
    },
    download(href, title) {
      const a = document.createElement("a");
      a.setAttribute("href", href);
      a.setAttribute("download", title);
      a.click();
    },
    // 获取单个图片信息
    // getFile(file, fileList) {
    //   const isLt05M = 1024 * 1024 * 0.5;
    //   let hasBig = file.size > isLt05M;
    //   if (hasBig) {
    //     this.fileList = [];
    //     this.$message.error("上传头像图片大小不能超过 500K!");
    //     return false;
    //   }
    //   this.fileForm = file.raw;
    //   let name = file.name.split(".");
    //   if (this.form.name === "") {
    //     this.form.name = name[0];
    //   }
    //   this.hideUpload = fileList.length >= this.limitCount;
    // },
    getFile(rawFile) {
      const params = new FormData();
      // params.append("personId", this.personId);
      params.append("fileType", 0);
      params.append("fileData", rawFile.raw);
      if (rawFile.size / 1024 / 1024 > 1) {
        this.$message.error("最大不超过1m!");
        this.$refs['uploadImg'].clearFiles()
        // this.getPersonFace();
        return false;
      }
      fileUploadApi(params).then((res) => {
        let path = ''
        if (res) {
          console.log(1137, res.path);
          // this.getPersonFace();
          this.facePath = res.path
          this.$message.success("上传成功");
        }
      });
    },
    // handleRemove(file, fileList) {
      // this.fileForm = undefined;
      // this.hideUpload = fileList.length >= this.limitCount;
    // },
    handleRemove(file, row) {
      this.getPersonFace();
      let self = this;
      let params = {
        // identityID: file.identityID ?? row.identityID,
        identityData: this.facePath
      };
      console.log(1211, file, row);
      this.facePath = '';
      this.form.identityData = '';
      delUploadPicApi(params).then((res) => {
        if (res) {
          this.$message.success("删除成功");
          this.getPersonFace();
        }
      })
      .catch((e) => {
        console.log(e);
        this.$message.warning("删除失败");
      });
    },
    async handlePictureCardPreview(file) {
      let fileUrl = await this.fileToBase64Async(file.raw)
      this.dialogImageUrl = fileUrl;
      this.dialogVisible = true;
    },
    // file转base64
    fileToBase64Async(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          resolve(e.target.result);
        };
      });
    },
    // ========================批量上传========================
    handleRemoveGroup(file, fileList) {
      this.fileListGroup = fileList;
    },
    handleSuccessGroup(response, file) {
      const isLt05M = 1024 * 1024 * 500;
      // let hasBig = file.some((v) => {
      //   return v.size > isLt05M
      // })
      // if (hasBig) {
      //   this.$message.error('上传头像图片大小不能超过 0.5MB!');
      // }
      // console.log(file[0])
      if (
        file[0].name.indexOf(".xls") == -1 &&
        file[0].name.indexOf(".xlsx") == -1
      ) {
        this.$message.error("必须上传.xls或者.xlsx文件！");
        this.fileListGroup = [];
        return false;
      }

      this.fileListGroup = file.filter((v, i) => {
        return v.size <= isLt05M;
      });
      let formData = new FormData();
      this.fileListGroup.map((c, i) => {
        formData.append("file", c.raw);
      });
      uploadPerson(formData)
        .then((res) => {
          console.log("res", res);
          this.$message.success("上传成功!");
          // this.dialogFormGroup = false;
          this.isUploadImageDisabled = false;
        })
        .catch((e) => {
          console.log(e);
          this.$message.warning("文件已发送但出现了错误，请联系后台管理员");
        });
    },
    handleExceed(file, fileList) {
      this.$message.warning("最大限度上传1个");
    },
    handleRemoveGroup2(file, fileList) {
      this.fileListGroup2 = fileList;
    },
    // 封装一个asyncPool,控制并发数
    asyncPool(fn, arr, limit = 2) {
      let that = this
      if (arr.length == 0) {
        this.msgError("请选择图片");
      }
      let args = [...arr]; //深拷贝arr
      let currentCount = 0; //当前运行的数量
      let results = [];
      let settledCount = 0;
      let order = 0;
      return new Promise((resolve, reject) => {
        function run() {
          that.fourthStepLoading = true
          while (currentCount < limit && args.length > 0) {
            currentCount++;
            (function (i) {
              console.log("当前请求数" + currentCount);
              let val = args.shift();
              fn(val)
                .then((v) => {
                  results[i] = v;
                })
                .finally(() => {
                  settledCount++;
                  currentCount--;
                  if (settledCount === arr.length) {
                    resolve(results);
                    that.fourthStepLoading = false
                  } else {
                    //注释run() 如果失败了，也不重新轮询
                    // 恢复run() 如果失败了，重新轮询
                    resolve(results);
                    run();
                    that.fourthStepLoading = false
                  }
                });
            })(order++);
          }
        }

        run();
      });
    },

    uploadImageApi(raw) {
      let formData = new FormData();
      formData.append("file", raw);
      return uploadImage(formData)
        .then((res) => {
          this.$message.success("图片上传成功!");
          this.totalSuccess++
          console.log(`output->res`, res)
          // this.dialogFormGroup = false;
        })
        .catch((e) => {
          // this.dialogFormGroup = false;
        });
    },
    handleSuccessGroup2(response, file) {
      const isLt05M = 1024 * 1024 * 500;
      // let arr = []
      // let hasBig = file.some((v) => {
      //   return v.size > isLt05M
      // })
      // if (hasBig) {
      //   this.$message.error('上传头像图片大小不能超过 0.5MB!');
      // }
      // console.log(file[0])
      if (
        file[0].name.indexOf(".png") == -1 &&
        file[0].name.indexOf(".jpeg") == -1 &&
        file[0].name.indexOf(".jpg") == -1 &&
        file[0].name.indexOf(".jp2") == -1 &&
        file[0].name.indexOf(".PNG") == -1 &&
        file[0].name.indexOf(".JPEG") == -1 &&
        file[0].name.indexOf(".JPG") == -1 &&
        file[0].name.indexOf(".JP2") == -1
      ) {
        this.$message.error("必须上传.jpg或者.jpeg文件.jp2文件或者.png文件！");
        this.fileListGroup2 = [];
        return false;
      }

      this.fileListGroup2 = file.filter((v, i) => {
        return v.size <= isLt05M;
      });
      this.isUploadImageDisabled2 = false;


    },
    handleImageUpload() {
      predictSubmitStatusApi({}).then((res) => {
        // console.log(res);
        // 0 被占用
        // this.isSubmitDisable = res.avilable == 0;
        this.progress = {...res};
        if (this.progress.avilable === 0) {
          this.$message.info("正在有人使用上传，请稍后");
        }
        // console.log("this.progress", this.progress);
      });
      if (this.progress.available != 1) {
        this.$message.warning('文件正在处理,请稍后再试')
        return false;
      }
      let arr = []
      this.fileListGroup2.forEach((c, i) => {
        arr.push(c.raw)
      });
      this.asyncPool(this.uploadImageApi, arr, 10).then(results => {
        console.log('results', results)
        this.isConfirmDisable = false
      }).catch(err => {
        console.log(err)
        this.isConfirmDisable = false
      })
    },
    handleExceed2(file, fileList) {
      this.$message.warning("最大限度上传10000张");
    },
    // 点击批量添加
    submitUploadGroup() {
      if (this.fileListGroup.length > 0 || this.fileListGroup2.length > 0) {
        // this.groupLoading = true;
        // console.log(
        //   this.activeName,
        //   this.fileListGroup.length,
        //   this.fileListGroup2.length
        // );
        if (this.activeName == "first" && this.fileListGroup.length > 0) {
          this.handleDialogFormGroupClose()
          // this.dialogFormGroup = false;
          // let formData = new FormData();
          // this.fileListGroup.map((c, i) => {
          //   formData.append("file", c.raw);
          // });
          // uploadPerson(formData).then((res) => {
          //   this.$message.success("上传成功!");
          //   this.dialogFormGroup = false;
          // });
        } else if (
          this.activeName == "first" &&
          this.fileListGroup2.length > 0
        ) {
          // this.dialogFormGroup = false;
          this.handleDialogFormGroupClose()
          // this.fileListGroup2.forEach((c, i) => {
          //   let formData = new FormData();
          //   formData.append("file", c.raw);
          //   uploadImage(formData).then((res) => {
          //     this.$message.success("上传成功!");
          //   });
          //   this.dialogFormGroup = false;
          // });
        }
      } else {
        this.msgError("请添加文件!");
      }
    },
    // 多个图片单独请求
    uploadGroupFileOne() {
      this.showprogress = true;
      this.percentage = 1;
      this.scaleTage = 100 / this.fileListGroup.length;
      let asyncFunc = (params, i, c_files) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (i % 5 == 0) {
              getFaceWaitingApi(new Date().getTime()).then(() => {
                setTimeout(() => {
                  getFaceWaitingApi(new Date().getTime()).then(() => {
                    setTimeout(() => {
                      this.getSingle(params, i, c_files);
                      resolve();
                    }, 200);
                  });
                }, 200);
              });
            } else {
              this.getSingle(params, i, c_files);
              resolve();
            }
          }, 200);
        });
      };
      let getFunc = async () => {
        for (let i = 0; i < this.fileListGroup.length; i++) {
          let params = {
            iAccessCardNumber: 0,
            sAddress: "",
            sBirthday: "1970-01-01",
            sCertificateNumber: "",
            sCertificateType: "identityCard",
            sGender: "unset",
            sHometown: "",
            sListType: "permanent",
            name: this.fileListGroup[i].name.replace(
              /.(jpg|jpeg|png|bmp|gif)/,
              ""
            ),
            sNation: "汉族",
            sNote: "undone",
            sTelephoneNumber: "",
            sType: "whiteList",
            loadCompleted: "",
          };
          await asyncFunc(params, i, this.fileListGroup[i].raw);
        }
      };
      getFunc();
    },
    // 循环单个请求中
    getSingle(params, b_i, c_files) {
      // 多个异步分开处理 先新增 再上传图片 再修改
      let hasRes = {};
      let a = () => {
        return new Promise((resolve, reject) => {
          addFacePersonsApi(params).then((response) => {
            hasRes = response;
            resolve(response);
          });
        });
      };

      let b = () => {
        return new Promise((resolve, reject) => {
          let formData = new FormData();
          formData.append("file", c_files);
          personsUploadApi(formData, hasRes.sLocalPicturePath)
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              resolve(err);
            });
        });
      };

      let c = () => {
        return new Promise((resolve, reject) => {
          params.sNote = "";
          editFacePersonsApi(params, hasRes.id)
            .then((res) => {
              // 请求完数组队列,最后一项需要检验
              if (this.isAdd == "add") {
                // 单个添加 获取特征值
                getLastStatus(res);
              } else {
                if (b_i == this.fileListGroup.length - 1) {
                  // 多组添加获取特征值
                  this.percentage = 100;
                  getLastStatus(res);
                } else {
                  this.percentage = accAdd(this.percentage, this.scaleTage);
                }
              }
              resolve(res);
            })
            .catch((err) => {
              this.groupLoading = false;
            });
        });
      };

      Promise.resolve()
        .then(() => {
          return a();
        })
        .then(() => {
          return b();
        })
        .then(() => {
          return c();
        })
        .catch(() => {
          return c();
        });

      // 小数相加
      function accAdd(arg1, arg2) {
        var r1, r2, m;
        try {
          r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
          r1 = 0;
        }
        try {
          r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
          r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
      }

      let _this = this,
        showTime = 12000,
        showTime_i = 4;
      // 配置单个和多个的时间间隔
      if (this.isAdd == "add") {
        showTime = 6000;
        showTime_i = 2;
      }

      function getLastStatus(data) {
        let instance = _this.$notify.success({
          title: "提示",
          message: "正在获取特征值中",
          showClose: false,
          duration: 0,
        });
        setTimeout(() => {
          _this.showprogress = false;
        }, 1000);
        // 循环请求最后一个 循环间隔获取状态
        for (let i = 0; i < showTime_i; i++) {
          setTimeout(() => {
            getFacePersonsApi(data.id, new Date().getTime()).then((re) => {
              if (i == showTime_i - 1) {
                instance.close();
                _this.uploadFileImgGroup();
              }
            });
          }, 3000 * i);
        }
      }
    },
    uploadFileImgGroup() {
      this.turnGetList();
      this.dialogFormGroup = false;
      this.groupLoading = false;
      this.dialogFormVisible = false;
      this.singleLoading = false;
      return false;
      // 请求完了检查失败的图片
      //TODO:在获取人员列表
      getFaceCheckIdsApi({id: this.checkId})
        .then((response) => {
          this.failList = response;
          if (this.failList.length > 0) {
            if (this.isAdd == "add") {
              this.singleLoading = false;
              this.$message.error("获得照片特征值失败，请更换照片");
            } else {
              this.dialogTableVisibleFail = true;
              // this.turnGetList();
            }
          } else {
            if (this.isAdd == "add") {
              this.$message.success("新增成功");
            }
            this.dialogFormVisible = false;
            this.turnGetList();
          }
          this.dialogFormGroup = false;
          this.groupLoading = false;
        })
        .catch((err) => {
          this.turnGetList();
          this.dialogFormGroup = false;
          this.groupLoading = false;
        });
    },
    turnGetList() {
      this.doGetCommunityPersons();
      setTimeout(() => {
        this.doGetCommunityPersons();
      }, 3000);
    },
    onClose() {
      this.$refs["dataForm"].resetFields();
    },
    // 更新进度条数量
    increase() {
      // this.intervalTime = setInterval(() => {
      // if (this.percentage > 99) {
      //     this.percentage = 100;
      // }else {
      //   this.percentage += 5;
      // }
      // }, 300);
    },
    // 进度条结束
    increaseend() {
      this.percentage = 100;
      clearInterval(this.intervalTime);
    },
  },
  computed: {
    ...mapGetters(["roleId"]),
    imgLimit() {
      return this.fileListGroup2 && this.fileListGroup2.length;
    },
    localOrigin() {
      return location.origin;
    },
  },
  destroyed() {
    clearInterval(this.intervalTime);
  },
};
</script>

<style lang="scss" scoped>
.filter-count {
  display: flex;
  justify-content: space-between;
}

/deep/ .hide .el-upload--picture-card {
  display: none;
}

.el-form-box {

  /deep/ {
    .numrule input::-webkit-outer-spin-button,
    .numrule input::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
    }

    .numrule input[type="number"] {
      -moz-appearance: textfield;
    }
  }
}

.pro-loading {
  //display: flex;
  //justify-content: flex-start;
  //align-content: center;
  //border: 1px solid red;
  padding-top: 10px;
  //margin: 0 0 10px 70px;
}
</style>
